package com.donquijote.spring6.Reflection;

import com.donquijote.spring6.annotation.Component;

import java.io.File;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 421527548@qq.com
 * @version V1.0
 * @title
 * @description
 * @date 2022-11-22 16:39
 */
public class ClassPathReflectionContext {


    public Map<String,Object> reflectObject(String packagePath) throws URISyntaxException {
        HashMap<String, Object> beanMap = new HashMap<>();
        //1、替换掉com.donquijote.spring6.bean 里面的 “.” 变成 “/”
        String path = packagePath.replaceAll("\\.", "/");

        //2、获取全部路径 ，路径中有中文的话 必须使用getResources().toURI() 来获取路径
        String allPath = ClassLoader.getSystemClassLoader().getResource(path).toURI().getPath();
        System.out.println(allPath);

        //3、创建file类，用来取出file文件里面的所有java文件
        File file = new File(allPath);

        //4、获取包下面的文件并且循环获取文件的路径
        File[] files = file.listFiles();
        Arrays.stream(files).forEach(beanFile -> {
            try {
                //5、将路径改造成适宜反射的样子com.donquijote.spring6.bean.Army
                String beanPath = packagePath + "." +beanFile.getName().split("\\.")[0];
                System.out.println(beanPath);
                Class<?> aClass = Class.forName(beanPath);
                //6、反射Component注解并且获取Bean对象
                if (aClass.isAnnotationPresent(Component.class)) {
                    String beanId = aClass.getAnnotation(Component.class).value();
                    Object newInstanceBean = aClass.getConstructor().newInstance();
                    beanMap.put(beanId,newInstanceBean);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } );
        return beanMap;
    }
}
